/**
 *
 */
package ua.ws.feedsreader.managers;

import java.io.BufferedReader;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import ua.ws.feedsreader.utils.Log;

import com.sun.syndication.feed.synd.SyndEntryImpl;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import ua.ws.feedsreader.db.SemanticManager;

/**
 * @author ricardo
 *
 */
public class FeedsManager {

    private List<String> stopWordList;

    public FeedsManager() {
    }

    private Collection<String> readConfig(String path) {
        Collection<String> sites = new ArrayList<>(1);
        try {
            BufferedReader reader = Files.newBufferedReader(Paths.get(path), Charset.forName("ISO-8859-1"));
            String line;
            while ((line = reader.readLine()) != null) {
                Log.debug("site: " + line);
                sites.add(line);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return sites;

    }
    /*
     * carrega todas as feeds no sistema.
     * @param path - caminho que contém os sites para ir carregar as feeds.
     */

    public void loadAllFeeds(String path) throws Exception {
        XmlReader reader;

        List<String> sites = (List<String>) readConfig(path);

        SemanticManager sm = new SemanticManager();

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        String dataActual = dateFormat.format(date);
        
        //carrega a stopWordList
        loadStopWordList();

        for (String site : sites) {
            Log.debug(" #################### " + site + " ############################");
            try {
                URL url = new URL(site);
                reader = new XmlReader(url);
                SyndFeed feedItem = new SyndFeedInput().build(reader);

                //percorre todas os items da rss
                for (Iterator it = feedItem.getEntries().iterator(); it.hasNext();) {

                    SyndEntryImpl entry = (SyndEntryImpl) it.next();
                    sm.insertNewFeedItem(entry.getTitle(), entry.getDescription().getValue(), entry.getLink(), dataActual, entry.getCategories(), this.stopWordList);
                }

            } catch (Exception e) {
                Log.error("From loadFeed:" + e.getMessage());
                e.printStackTrace();
            }

            //Log.debug(" ################################################ " + site);
        }
    }

    /*
     * Faz o carregamento de uma lista de Stopwords.
     * @Param path - caminho do ficheiro que contém as stop words.
     */
    private void loadStopWordList() throws Exception {
        String path = null;
        stopWordList = new ArrayList<>();

        try {
            path = new File("./..").getCanonicalPath() + "/webapps/feedsreader/WEB-INF/classes/configurations/StopListPortuguese.txt";
        } catch (IOException e) {
            throw new Exception("Erro no carregamento do ficheiro StopListPortuguese.txt");
        }


        try {
            BufferedReader reader = Files.newBufferedReader(Paths.get(path), Charset.forName("ISO-8859-1"));
            String line;
            while ((line = reader.readLine()) != null) {                
                if (!stopWordList.contains(line)) {
                    stopWordList.add(line);
                }
            }
        } catch (IOException e) {
            throw new Exception("Erro no carregamento da stopWordList");
        }
    }

    public List<String> getStopWordList() {
        return stopWordList;
    }
    
    
}
